package cn.bonoon.controllers.schedule;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.bonoon.core.plugins.HolidayService;
import cn.bonoon.core.plugins.PersonalHolidayService;
import cn.bonoon.core.plugins.ScheduleService;
import cn.bonoon.entities.plugins.PersonalHolidayEntity;
import cn.bonoon.entities.plugins.ScheduleEntity;
import cn.bonoon.kernel.util.StringHelper;
import cn.bonoon.kernel.web.models.JsonResult;

/**
 * 日程安排-月视图
 * @author ocean~
 */
@Controller
@RequestMapping("s/user/schedule")
public class ScheduleMonthViewController extends AbstractSchedule {

	@Autowired
	public ScheduleMonthViewController(HolidayService holidayService, PersonalHolidayService personalHolidayService, ScheduleService scheduleService) {
		super(holidayService, personalHolidayService, scheduleService);
	}
	
	@RequestMapping(value = "view/month", method = { POST, GET })
	public String monthView(Model model, HttpServletRequest request, Integer year, Integer month) {
		if (null == year) {
			year = Calendar.getInstance().get(Calendar.YEAR);
		}
		if (null == month) {
			if (year == Calendar.getInstance().get(Calendar.YEAR)) {				
				month = Calendar.getInstance().get(Calendar.MONTH);
			} else {
				month = 0;
			}
		}
		model.addAttribute("content", viewMonth(year, month));
		return "user/schedule/schedule-view-month";
	}
	
	@ResponseBody
	@RequestMapping(value = "view/refresh_month", method = { RequestMethod.GET, RequestMethod.POST })
	public JsonResult refresh_monthView(Integer year, Integer month, Model model) {
		if (null == year) {
			year = Calendar.getInstance().get(Calendar.YEAR);
		}
		if (null == month) {
			Calendar.getInstance().get(Calendar.MONTH);
		}
		return JsonResult.result(viewMonth(year, month));
	}
	
	@ResponseBody
	@RequestMapping(value = "view/month_today", method = { RequestMethod.GET, RequestMethod.POST })
	public JsonResult view_month_today(Model model) {
		Calendar cal = Calendar.getInstance();
		return JsonResult.result(viewMonth(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)));
	}
	
	private String viewMonth(int year, int month) {
		StringBuilder content = new StringBuilder();
		// -------------------- thead --------------------
		content.append("<tr>");
		content.append("<td colspan='7' style='text-align:center;height:50px;'>");
		content.append("<span style='float:left;'>");
		content.append("<a href='#' class='bupabutton' data-settings='flat:true' id='a_today'>今天</a>&nbsp;");
		content.append("年份：<select style='width:100px;' id='sel_year'>");
		int current_year = Calendar.getInstance().get(Calendar.YEAR);
		for (int i = current_year; i < (current_year + 10); i++) {
			if (i == year) {
				content.append("<option value='" + i + "' selected='selected'>" + i + "</option>");
			} else {
				content.append("<option value='" + i + "'>" + i + "</option>");
			}
		}
		content.append("</select>&nbsp;&nbsp;");
		content.append("月份：<select style='width:100px;' id='sel_month'>");
		for (int i = 0; i < 12; i++) {
			if (i == month) {
				content.append("<option value='" + i + "' selected='selected'>" + (i+1) + "</option>");
			} else {
				content.append("<option value='" + i + "'>" + (i+1) + "</option>");
			}
		}
		content.append("</select>&nbsp;&nbsp;<a href=\"#\" class='bupabutton' data-settings='flat:true' id='a_ok'>确定</a>");
		content.append("</span>");
		content.append("<strong><span style='font-size:16px;'><span id='title_year'>").append(year).append("</span>年");
		content.append("<span id='title_month' style='display:inline-block;width:18px;'>").append(month + 1).append("</span>月行程安排</span></strong>");
		content.append("<span style='float:right;'>");
		content.append("<img src='/res/images/holiday.png'/>：公共节假日&nbsp;&nbsp;");
		content.append("<img src='/res/images/windmill.png'/>：个人假日&nbsp;&nbsp;");
		content.append("<img src='/res/images/detail.png' />：行程日志&nbsp;&nbsp;&nbsp;");
		content.append("<a href=\"#\" class=\"bupabutton\" data-settings='flat:true' id=\"a_weekview\">&nbsp;周&nbsp;</a>");
		content.append("<a href=\"#\" class=\"bupabutton\" data-settings='flat:true' id=\"a_monthview\" data-settings=\"selected:true\">&nbsp;月&nbsp;</a>");
		content.append("<a href=\"#\" class=\"bupabutton\" data-settings='flat:true' id=\"a_yearview\">&nbsp;年&nbsp;</a>");
		content.append("</span></td></tr>");
		content.append("<tr>");
		content.append("<th style='width:100px;text-align:center;'>日</th>"); // background-color:#0C3;
		content.append("<th style='width:100px;text-align:center;'>一</th>");
		content.append("<th style='width:100px;text-align:center;'>二</th>");
		content.append("<th style='width:100px;text-align:center;'>三</th>");
		content.append("<th style='width:100px;text-align:center;'>四</th>");
		content.append("<th style='width:100px;text-align:center;'>五</th>");
		content.append("<th style='width:100px;text-align:center;'>六</th>");
		content.append("</tr>");
		// -------------------- tbody --------------------
		String m_days = holidayService.getMonth(year, month);
		List<PersonalHolidayEntity> personalHolidays = personalHolidayService.getMonth(getUser(), year, month);
		List<ScheduleEntity> schedules = scheduleService.getMonth(getUser(), year, month);
		Calendar c = Calendar.getInstance();
		c.set(year, month, 1);
		int day_count = c.getActualMaximum(Calendar.DAY_OF_MONTH); // 当前月的天数
		int week_of_minday = c.get(Calendar.DAY_OF_WEEK); // 当月第一天是星期几
		
		int[] tips_sc = new int[day_count]; // 显示行程安排的数量
		int[] tips_ph = new int[day_count]; // 显示个人假期的数量
		int[] holidays = null;
		int holidays_len = 0;
		if (StringHelper.isNotEmpty(m_days)) {
			holidays = StringHelper.tointArray(m_days);
			holidays_len = holidays.length;
		}
		int week = week_of_minday;
		
		content.append("<tr>");
		for (int i = 1; i < week_of_minday; i++) {
			content.append("<td></td>");
		}
		for (int i = 1, index = 0; i <= day_count; i++) {
			if (null != holidays) {
				if (index < holidays_len && holidays[index] == i) {
					content.append("<td style='text-align:left;cursor:default;position:relative;height:115px;' valign='top' class='day selectedDay'>");
					index++;
				} else {
					content.append("<td style='text-align:left;cursor:default;position:relative;height:115px;' valign='top' class='day'>");
				}
			} else {
				if (week == 1 || week == 7) {
					content.append("<td style='text-align:left;cursor:default;position:relative;height:115px;' valign='top' class='day selectedDay'>");
				} else {
					content.append("<td style='text-align:left;cursor:default;position:relative;height:115px;' valign='top' class='day'>");
				}
			}
			content.append("<input type='hidden' class='month").append(month).append("' value='").append(i).append("' />");
			content.append(i).append("<br/>");
			// 当天是否存在行程安排
			if (null != schedules) {
				boolean img_flag = false;
				for (int j = schedules.size() - 1; j >= 0 ; j--) {
					ScheduleEntity s = schedules.get(j);
					Calendar executeAt = Calendar.getInstance();
					executeAt.setTime(s.getExecuteAt());
					boolean hasSchedules = executeAt.get(Calendar.YEAR) == year && executeAt.get(Calendar.MONTH) == month && executeAt.get(Calendar.DATE) == i;
					if (!img_flag && hasSchedules) {
						content.append("<img src='/res/images/detail.png' name='img_schedule' style='position:absolute;right:40px;top:0;'/>");
						img_flag = true;
					}
					if (hasSchedules && tips_sc[i] < 2) {
						String name = s.getName();
						name = name.length() > 11 ? name.substring(0, 11) + "..." : name;
						content.append(name).append("<br/>");
						tips_sc[i]++;
					}
				}
//				for (ScheduleEntity s : schedules) {
//					Calendar executeAt = Calendar.getInstance();
//					executeAt.setTime(s.getExecuteAt());
//					if (executeAt.get(Calendar.YEAR) == year && executeAt.get(Calendar.MONTH) == month && executeAt.get(Calendar.DATE) == i) {
//						content.append("<img src='/res/images/detail.png' name='img_schedule' style='position:absolute;right:40px;top:0;'/>");
//						break;
//					}
//				}
			}
			// 当天是否开始个人假日（持续N天）
			if (null != personalHolidays) {
				boolean img_flag = false;
				for (int j = personalHolidays.size() - 1; j >= 0 ; j--) {
					PersonalHolidayEntity ph = personalHolidays.get(j);
					boolean hasPh = ph.getYear() == year && ph.getMonth() == month && ph.getDate() == i;
					if (!img_flag && hasPh) {
						content.append("<img src='/res/images/windmill.png' name='img_personalHoliday' style='position:absolute;right:20px;top:0;' />");
						img_flag = true;
					}
					if (hasPh && tips_ph[i] < 2) {
						int type = ph.getType();//（0.请假/事假； 1.病假； 2.年假； 3.加班； 4.缺席；）
						String tips = type == 0 ? "请假/事假" : type == 1 ? "病假" : type == 2 ? "年假" : type == 3 ? "加班" : type == 4 ? "缺席" : "其它";
						tips = tips.length() > 11 ? tips.substring(0, 11) + "..." : tips;
						content.append(tips).append("<br/>");
						tips_ph[i]++;
					}
				}
//				for (PersonalHolidayEntity ph : personalHolidays) {
//					if (ph.getYear() == year && ph.getMonth() == month && ph.getDate() == i) {
//						content.append("<img src='/res/images/windmill.png' name='img_personalHoliday' style='position:absolute;right:20px;top:0;' />");
//						break;
//					}
//				}
			}
			content.append("</td>");
			if (week == 7) {
				content.append(day_count == i ? "</tr>" : "</tr><tr>");
			}
			if (++week > 7) {
				week = 1;
			}
		}
		week = --week < 1 ? 7 : week; // 当月最后一天的星期
		if (week != 7) {
			content.append("<td colspan='" + (7 - week) + "'></td>");
			content.append("</tr>");
		}
		content.append("<input id='year' type='hidden' value='").append(year).append("'/>");
		content.append("<input id='month' type='hidden' value='").append(month).append("'/>");
		content.append("<input id='date' type='hidden' />");
		return content.toString();
	}
}
